package com.baomidou.springwind.excel;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.springwind.entity.*;
import com.baomidou.springwind.mapper.InventoryCostAfterDao;
import com.baomidou.springwind.mapper.NetworkLngLatDao;
import com.baomidou.springwind.mapper.NetworkSaleLngLatDao;
import com.baomidou.springwind.mapper.SysAreaDao;
import com.baomidou.springwind.service.FlowAnalysisService;
import com.baomidou.springwind.service.InventoryCostAfterService;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;

/**
 * excel文件读取
 *
 * @author luox
 */
@Component
public class InventoryCostAfterDataReader extends ExcelReader<InventoryCostAfter> {

    @Autowired
    private InventoryCostAfterDao inventoryCostAfterDao;//
    @Autowired
    private NetworkLngLatDao networkLngLatDao;//地区Dao
    @Autowired
    private SysAreaDao sysAreaDao;//地区Dao
    @Autowired
    private InventoryCostAfterService inventoryCostAfterService;
    @Override
    protected String saveData(List<InventoryCostAfter> dataList, Long batchId) {
        EntityWrapper<InventoryCostAfter> wrapper = new EntityWrapper<InventoryCostAfter>();
        wrapper.eq("batch_id", batchId);
        deleteInventoryCostFile(batchId);
        inventoryCostAfterService.delete(wrapper);//删除之前导入的数据
        for (InventoryCostAfter inventoryCostAfter : dataList) {
            inventoryCostAfter.setBatchId(batchId);
            inventoryCostAfter.setCreateTime(new Date());
            inventoryCostAfter.setOperatorId(getCurrentUserId());
        }
        inventoryCostAfterService.insertBatch(dataList, 100);
        //处理工厂到配送中心的时间
        EntityWrapper<InventoryCostAfter> factoryToBranch = new EntityWrapper<InventoryCostAfter>();
        factoryToBranch.eq("batch_id", batchId);
        factoryToBranch.groupBy("branch_id");
        factoryToBranch.groupBy("factory_id");
        List<InventoryCostAfter> factoryToBranchs=inventoryCostAfterService.selectList(factoryToBranch);
        for (int i=0;i<factoryToBranchs.size();i++){
            EntityWrapper<NetworkLngLat> wrapper1 = new EntityWrapper<NetworkLngLat>();
            wrapper1.eq("id", factoryToBranchs.get(i).getFactoryId());
            List<NetworkLngLat> latlng1=networkLngLatDao.selectList(wrapper1);
            EntityWrapper<NetworkLngLat> wrapper2 = new EntityWrapper<NetworkLngLat>();
            wrapper2.eq("id", factoryToBranchs.get(i).getBranchId());
            List<NetworkLngLat> latlng2=networkLngLatDao.selectList(wrapper2);
//            StringBuilder originsParam=new StringBuilder();
//            BigDecimal zuobiaoY1 =BigDecimal.valueOf(Double.valueOf(latlng1.get(0).getLat()));
//            BigDecimal zuobiaoX1 = BigDecimal.valueOf(Double.valueOf(latlng1.get(0).getLng()));
//            StringBuilder destinationsParam1=new StringBuilder();
//            originsParam.append(zuobiaoX1.setScale(2, BigDecimal.ROUND_HALF_UP));
//            originsParam.append(",");
//            originsParam.append(zuobiaoY1.setScale(2, BigDecimal.ROUND_HALF_UP));
//            destinationsParam1.append(BigDecimal.valueOf(Double.valueOf(latlng2.get(0).getLng())).setScale(2, BigDecimal.ROUND_HALF_UP));
//            destinationsParam1.append(",");
//            destinationsParam1.append(BigDecimal.valueOf(Double.valueOf(latlng2.get(0).getLat())).setScale(2, BigDecimal.ROUND_HALF_UP));
//            String juli=TwoJuLi(originsParam,destinationsParam1);
            double juli=Node1ToNode2Distance(Double.valueOf(latlng1.get(0).getLat()),Double.valueOf(latlng1.get(0).getLng()),Double.valueOf(latlng2.get(0).getLat()),Double.valueOf(latlng2.get(0).getLng()));
            int time=0;
            time=1+(int)juli/60/24;
            Map<String,Object> pm=new HashMap<String,Object>();
            pm.put("branch_id",factoryToBranchs.get(i).getBranchId());
            pm.put("factory_id",factoryToBranchs.get(i).getFactoryId());
            pm.put("batch_id",batchId);
            pm.put("time",time);
            inventoryCostAfterDao.updateTime(pm);
        }
        return "";
    }

    private void deleteInventoryCostFile(Long batchId) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String path = request.getSession().getServletContext().getRealPath("");
        path = path.substring(0, path.lastIndexOf("\\"));
        path = path.substring(0, path.lastIndexOf("\\"));
        File file = new File(path + "/temp/route/" + batchId + ".obj");
        file.delete();
    }

    @Override
    protected List<InventoryCostAfter> verifyData(HSSFWorkbook workbook) {
        List<InventoryCostAfter> inventoryCostAfters = new ArrayList<InventoryCostAfter>();
        HSSFSheet sheet = workbook.getSheetAt(0);
        int lastRowNum = sheet.getLastRowNum();
        InventoryCostAfter inventoryCostAfter;
        for (int i = 1; i <= lastRowNum; i++) {
            sheet.getRow(i);
            inventoryCostAfter = new InventoryCostAfter();

            inventoryCostAfter.setBranchCenter(getStringCellValue( sheet.getRow(i), 0));
            /*
            调用百度地图或者工具来出来地图坐标问题，一级配送中心地图处理
             */
            EntityWrapper<NetworkLngLat> wrapperBranch = new EntityWrapper<NetworkLngLat>();
            wrapperBranch.eq("name", getStringCellValue(sheet.getRow(i), 0).replace("工贸",""));
            List<Map<String, Object>> networkLngLatBranch=networkLngLatDao.selectMaps(wrapperBranch);
            if (networkLngLatBranch.size()>0){
                inventoryCostAfter.setBranchId(Long.valueOf(networkLngLatBranch.get(0).get("id").toString()));
            }else{
                JSONArray jsonArray=latlng(getStringCellValue(sheet.getRow(i), 0));
                NetworkLngLat networkLngLatbran=new NetworkLngLat();
                networkLngLatbran.setName(getStringCellValue(sheet.getRow(i), 0).replace("工贸",""));
                networkLngLatbran.setLng(jsonArray.get(0).toString());
                networkLngLatbran.setLat(jsonArray.get(1).toString());
                networkLngLatDao.insert(networkLngLatbran);
                EntityWrapper<NetworkLngLat> wrapperBranch2 = new EntityWrapper<NetworkLngLat>();
                wrapperBranch2.eq("name", getStringCellValue(sheet.getRow(i), 0).replace("工贸",""));
                List<Map<String, Object>> networkLngLatBranch2=networkLngLatDao.selectMaps(wrapperBranch2);
                inventoryCostAfter.setBranchId(Long.valueOf(networkLngLatBranch2.get(0).get("id").toString()));
            }
            inventoryCostAfter.setDeliveryCenter(getStringCellValue(sheet.getRow(i), 1));
            /*
            调用百度地图或者工具来出来地图坐标问题，二级配送中心地图处理
             */
            EntityWrapper<SysArea> wrapperDelivery = new EntityWrapper<SysArea>();
            wrapperDelivery.eq("shortname", getStringCellValue(sheet.getRow(i), 1));
            List<Map<String, Object>> networkLngLatDelivery=sysAreaDao.selectMaps(wrapperDelivery);
            if (networkLngLatDelivery.size()>0){
                inventoryCostAfter.setDeliveryId(Long.valueOf(networkLngLatDelivery.get(0).get("id").toString()));
            }
            inventoryCostAfter.setFactoryName(getStringCellValue(sheet.getRow(i), 2));
             /*
            调用百度地图或者工具来出来地图坐标问题，一级配送中心地图处理
             */
            EntityWrapper<NetworkLngLat> wrapperFactory = new EntityWrapper<NetworkLngLat>();
            wrapperFactory.eq("name", getStringCellValue(sheet.getRow(i), 2));
            List<Map<String, Object>> networkLngLatFactory=networkLngLatDao.selectMaps(wrapperFactory);
            if (networkLngLatFactory.size()>0){
                inventoryCostAfter.setFactoryId(Long.valueOf(networkLngLatFactory.get(0).get("id").toString()));
            }else{
                JSONArray jsonArray=latlng(getStringCellValue(sheet.getRow(i), 2));
                NetworkLngLat networkLngLatbran=new NetworkLngLat();
                networkLngLatbran.setName(getStringCellValue(sheet.getRow(i), 2));
                networkLngLatbran.setLng(jsonArray.get(0).toString());
                networkLngLatbran.setLat(jsonArray.get(1).toString());
                networkLngLatDao.insert(networkLngLatbran);
                EntityWrapper<NetworkLngLat> wrapperBranch2 = new EntityWrapper<NetworkLngLat>();
                wrapperBranch2.eq("name", getStringCellValue(sheet.getRow(i), 2));
                List<Map<String, Object>> networkLngLatBranch2=networkLngLatDao.selectMaps(wrapperBranch2);
                inventoryCostAfter.setFactoryId(Long.valueOf(networkLngLatBranch2.get(0).get("id").toString()));
            }


            inventoryCostAfter.setOrderQuantity(getIntCellValue(sheet.getRow(i), 3));
            inventoryCostAfter.setPreparationCar(getDateCellValue(sheet.getRow(i), 4));
            inventoryCostAfter.setCarArrive(getDateCellValue(sheet.getRow(i), 5));
            inventoryCostAfter.setPromiseArrival(getDateCellValue(sheet.getRow(i),6));
            inventoryCostAfters.add(inventoryCostAfter);
        }
        return inventoryCostAfters;
    }



    //通过地址名来获取到经纬度,调用百度地图来处理的
    private JSONArray latlng(String placename){
        placename=placename.replace("工贸","");
        JSONArray jsonArray=new JSONArray();
        placename=placename+"市";
        String url = String.format("http://api.map.baidu.com/geocoder?address=%s&output=json&key=%s", URLEncoder.encode(placename.toString()),"NURx5GUAQ1IBZVBMCQSpYppRsDdTpbxG");
        CloseableHttpClient client = HttpClients.createDefault();
        double lng=0;
        double lat=0;
        System.out.println(placename+"-------");
        try {
            HttpGet httpGet = new HttpGet(url);
            HttpResponse httpResponse = client.execute(httpGet);

            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                HttpEntity httpEntity = httpResponse.getEntity();
                String text = EntityUtils.toString(httpEntity);//取出应答字符串
                JSONObject json = JSONObject.parseObject(text);
                lng = json.getJSONObject("result").getJSONObject("location").getDouble("lng");
                lat = json.getJSONObject("result").getJSONObject("location").getDouble("lat");
                jsonArray.add(lng);
                jsonArray.add(lat);
                return jsonArray;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    //调用百度api接口，返回距离
    public  String TwoJuLi(StringBuilder originsParam,StringBuilder destinationsParam){
        //调用百度地图api
        List<JSONObject> result = new ArrayList<JSONObject>();
        //   destinationsParam.deleteCharAt(destinationsParam.lastIndexOf("|"));
        String url = String.format("http://api.map.baidu.com/routematrix/v2/driving?output=json&origins=%s&destinations=%s&ak=%s", URLEncoder.encode(originsParam.toString()), URLEncoder.encode(destinationsParam.toString()), "NURx5GUAQ1IBZVBMCQSpYppRsDdTpbxG");
        String Juli=null;
        CloseableHttpClient client = HttpClients.createDefault();
        try {
            HttpGet httpGet = new HttpGet(url);
            HttpResponse httpResponse = client.execute(httpGet);
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                HttpEntity httpEntity = httpResponse.getEntity();
                String text = EntityUtils.toString(httpEntity);//取出应答字符串
                JSONObject json = JSONObject.parseObject(text);

                String i1=null;
                JSONArray array = json.getJSONArray("result");

                JSONObject distance = array.getJSONObject(0);
                //   distance.put("node", destinations.get(i));
                //   result.add(distance);
                Juli=distance.getJSONObject("distance").getString("text");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Juli;

    }
    //根据2个点的经纬度算出他们的直线距离
    public  double Node1ToNode2Distance(double wd1,double jd1,double wd2,double jd2)
    {
        double x,y,out;
        double PI=3.14159265;
        double R=6.371229*1e6;

        x=(jd2-jd1)*PI*R*Math.cos( ((wd1+wd2)/2) *PI/180)/180;
        y=(wd2-wd1)*PI*R/180;
        out=Math.hypot(x,y);
        return out/1000;
    }

    @Override
    protected List<InventoryCostAfter> verifyData7(XSSFWorkbook workbook) {
        return null;
    }
}
